/**
 * 游戏列表菜单的管理
 */
(function() {
    var gameList = function() {
        var self = this;
    };
    gameList.prototype = {};

    gameList.prototype.init = function(cb) {
        var self = this;
        
        // 服务器的配置
        self.pull(function() {
            self.draw();
            if (cb) cb();
        });
    }

    gameList.prototype.pull = function(cb) {
        var self = this;
        self.menus = [];
        if (window.localStorage) {
            // 先从本地读取
            var v1 = localStorage.getItem(urlInfo.host + "/remote_games");
            var v2 = localStorage.getItem(urlInfo.host + "/remote_games_time");
            if (v1 && v2 && new Date().getTime() - v2 < 120 * 60 * 100) {
                // 有效期为2分钟
                self.menus = JSON.parse(v1);
            }
        }

        if (Util.isEmpty(self.menus)) {
            Classify.queryExt("games", "order", true, {}, function(r) {
                for (var i in r) {
                    if (r[i] < 0) continue;
                    self.menus.push({
                        game: i,
                        order: r[i],
                    });
                    self.menus.sort(function(a, b) {
                        var aorder = a.order, border = b.order;
                        return aorder - border;
                    });
                }
                cb();
            });
        }
        else cb();
    }

    gameList.prototype.draw = function() {
        var self = this;
        var curr = window.game || urlInfo.params.game || 'bjpk10';
        if (self.menus[curr] < 0) {
            // 这个游戏关闭了，需要使用另外一个
            for (var k in self.menus) {
                if (self.menus[k] > 0) {
                    curr = k;
                    break;
                }
            }
        }

        // 设置为当前的游戏
        window.game = curr;

        // 填充菜单
        $("#system-menus .games").empty();
        var f = function(key, name, c) {
            var l = '<a value="__k__" href="#">__name__</a>';
            l = l.replace(/__k__/g, key);
            l = l.replace(/__name__/g, name);
            if (!c) {
                $("#system-menus .games").append(l);
            }
            else
                c.append(l);
        }
        var list = self.menus;
        for (var i = 0; i < list.length; i++) {
            if (!list[i]) continue;
            f(list[i].game, get_game_display_name(list[i].game));
        }
    
        var cb = function(e) {
            var target = $(e.currentTarget);
            var g = target.attr("value");
            if (window.game == g) return;
            switchGame(g);
            __hideAni();
        };
        $("#system-menus .games a").click(cb);
        $("#system-menus .back2hall").click(function() {
            Util.jumpUrl({
                file: 'center.html',
                cmd: 'gamecenter',
            });
        });
    }

    window.GameList = new gameList();
})();
